package com.petadoption.serverclient.controller;

import com.petadoption.serverclient.entity.Orderlist;
import com.petadoption.serverclient.entity.Productlist;
import com.petadoption.serverclient.service.IOrderlistService;
import com.petadoption.serverclient.service.IProductlistService;
import com.petadoption.serverclient.utils.Result;
import com.petadoption.serverclient.utils.TokenUtil;
import com.petadoption.serverclient.vo.ProductlistVO;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderlistController {
    @Resource
    private Result result;

    @Resource
    private IOrderlistService orderlistService;
    @Resource
    private IProductlistService productlistService;


    @PostMapping("/addOrder")
    public Result addOrder(@RequestBody ProductlistVO productlistVO) {
        Integer userId = TokenUtil.getCurrenUser().getUserId();
        Productlist productlist = new Productlist();
        productlist.setProductlistAddress(productlistVO.getProductlistAddress());
        productlist.setProdeuctlistUser(userId);
        productlist.setProductlistTime(LocalDate.now());
        int productListId = productlistService.addProductList(productlist);
        System.out.println("订单ID：" + productListId);


        productlist.setProductlistOrderlist(productListId);
        int i = productlistService.updateProductList(productlist);
        if (i < 0) return result.fail("订单创建失败");
        List<Orderlist> list = productlistVO.getProductlistOrderlist();
        list.forEach(orderlist ->
                {
                    orderlist.setOrderlistProductlist(productListId);
                    orderlist.setOrderlistUser(userId);
                    orderlistService.addOrderList(orderlist);
                }
        );
        return result.success("订单创建成功");
    }
}
